package com.kxf.androidtestdemo.activity;

import static com.kxf.androidtestdemo.activity.RegisterForActivityResultActivity.MSG_CONN_SUCCESS;
import static com.kxf.androidtestdemo.activity.RegisterForActivityResultActivity.MSG_DIS_CONN;
import static com.kxf.androidtestdemo.activity.RegisterForActivityResultActivity.MSG_FROM_CLIENT;
import static com.kxf.androidtestdemo.activity.RegisterForActivityResultActivity.MSG_KEY;
import static com.kxf.androidtestdemo.activity.RegisterForActivityResultActivity.MSG_TO_CLIENT;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
import android.view.View;

import com.kxf.androidtestdemo.R;
import com.kxf.androidtestdemo.bean.ActivityResultCallbackBean;
import com.kxf.androidtestdemo.interfaces.IRemoteActivityCallback;
import com.kxf.androidtestdemo.view.LogTxtView;
import com.kxf.utils.Util;

import java.lang.ref.WeakReference;

public class RemoteServiceActivity extends BaseActivity {

    private LogTxtView logTxtView;
    private Messenger mCallbackMsg;
    private ActivityResultCallbackBean bean;

    private HandlerThread handlerThread;
    private Handler handleMessage;
    private Messenger mServiceMessenger;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remote_service);
        logTxtView = findViewById(R.id.logTxtView);


        IBinder binderMsg = null;
        if (getIntent()!=null && getIntent().getExtras()!=null){
            binderMsg = getIntent().getExtras().getBinder(MSG_KEY);
        }
        if (binderMsg != null) {
            handlerThread = new HandlerThread(MSG_KEY + "_main");
            handlerThread.start();
            handleMessage = new Handler(handlerThread.getLooper()) {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    Bundle data = msg.getData();
                    logTxtView.showTxt(Thread.currentThread().getName() + "  RemoteServiceActivity handleMessage  MSG_FROM_CLIENT=" + Util.getBundleToString(data));
                    switch (msg.what) {
                        case MSG_FROM_CLIENT:
//                    String result = (String) msg.obj;
                            break;
                    }
                }
            };
            mServiceMessenger = new Messenger(handleMessage);
            mCallbackMsg = new Messenger(binderMsg);
            Message message = Message.obtain();
            message.what = MSG_CONN_SUCCESS;
            Bundle bundle = new Bundle();
            bundle.putInt("code", 200);
            bundle.putString("resultStr", "MSG_CONN_SUCCESS");
            bundle.putBinder(MSG_KEY, mServiceMessenger.getBinder());
            message.replyTo = mServiceMessenger;
            message.setData(bundle);
            try {
                mCallbackMsg.send(message);
                logTxtView.showTxt("mCallbackMsg  send=");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        bean = new ActivityResultCallbackBean();
        bean.setCode(1024);
        bean.setResultStr("RemoteServiceActivity18721314176");
        logTxtView.showTxt("onCreate======##>>>>>>" + android.os.Process.myPid() + "   getTaskId()=" + getTaskId());
    }

    public void onClickBack(View view) {
        callBackResult();
        finish();
    }

    public void callBackResult() {
        Intent intent = new Intent();
        intent.putExtra("code", bean.getCode());
        intent.putExtra("resultStr", bean.getResultStr());
        setResult(RESULT_OK, intent);
        if (RegisterForActivityResultActivity.remoteActivityCallback != null) {
            IRemoteActivityCallback callback = RegisterForActivityResultActivity.remoteActivityCallback.get();
            if (callback != null) {
                callback.callback(bean);
            } else {
                Log.e("RemoteServiceActivity", "RegisterForActivityResultActivity.remoteActivityCallback  callback== null");
            }
            RegisterForActivityResultActivity.remoteActivityCallback = null;
        } else {
            Log.e("RemoteServiceActivity", "RegisterForActivityResultActivity.remoteActivityCallback == null");
        }
    }

    public void onClickBackMsg(View view) {
        Message message = Message.obtain();
        message.what = MSG_TO_CLIENT;
        Bundle bundle = new Bundle();
        bundle.putInt("code", bean.getCode());
        bundle.putString("resultStr", bean.getResultStr());
        message.setData(bundle);
        try {
            mCallbackMsg.send(message);
            logTxtView.showTxt("mCallbackMsg  send=");
        } catch (Exception e) {
            e.printStackTrace();
        }

//        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        Message message = Message.obtain();
        message.what = MSG_DIS_CONN;
        Bundle bundle = new Bundle();
        bundle.putInt("code", -4);
        bundle.putString("resultStr", "DIS_CONN");
        message.setData(bundle);
        try {
            mCallbackMsg.send(message);
            logTxtView.showTxt("MSG_DIS_CONN mCallbackMsg  send=");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (handlerThread!=null){
            handlerThread.quitSafely();
        }
        mServiceMessenger = null;
    }

    public void onClickException(View view) {
        throw new RuntimeException("");
    }
}